package com.br.aiops.alert;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class K8sUtils {

    public static final String RESULT = "result";
    public static final String DATA = "data";
    public static final String CODE = "code";
    private String podListUrl = "/api/v1/k8s/pod?cluster_id=%s&app_name=%s&namespace=default&page_size=1000";

    private String nodeListUrl = "/api/v1/k8s/pod?cluster_id=%s&app_name=%s&namespace=default&page_size=1000";

    @Value("${k8s.url}")
    private String url;

    public JSONArray getPods(String cluster, String service) {
        String requestUrl = String.format(String.join("", url, podListUrl), cluster, service);
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .writeTimeout(5, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder().url(requestUrl).get().build();
        try {
            Response response = client.newCall(request).execute();
            if (Objects.equals(response.code(), 200)) {
                String body = response.body().string();
                JSONObject bodyJson = JSONObject.parseObject(body);
                boolean success = Objects.equals(bodyJson.getInteger(CODE), 200);
                if (success) {
                    return bodyJson.getJSONObject(RESULT).getJSONArray(DATA);
                }
            }
        } catch (IOException e) {
            log.warn("获取pod数据失败！");
        }

        return new JSONArray();
    }
}
